

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>使用 Flask 设计 RESTful 的认证 &mdash; Designing a RESTful API with Python and Flask 1.0 documentation</title>
  

  
  

  
  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

  
  
    

  

  
  
    <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  

  
    <link rel="top" title="Designing a RESTful API with Python and Flask 1.0 documentation" href="index.html"/>
        <link rel="prev" title="使用 Flask-RESTful 设计 RESTful API" href="second.html"/> 

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script>

</head>

<body class="wy-body-for-nav" role="document">

  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-nav-search">
        
          <a href="index.html" class="fa fa-home"> Designing a RESTful API with Python and Flask</a>
        
        
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>
      </div>

      <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
        
          
          
              <ul class="current">
<li class="toctree-l1"><a class="reference internal" href="first.html">使用 Python 和 Flask 设计 RESTful API</a><ul>
<li class="toctree-l2"><a class="reference internal" href="first.html#rest">什么是 REST？</a></li>
<li class="toctree-l2"><a class="reference internal" href="first.html#restful-web-service">什么是一个 RESTful 的 web service？</a></li>
<li class="toctree-l2"><a class="reference internal" href="first.html#web-service">设计一个简单的 web service</a></li>
<li class="toctree-l2"><a class="reference internal" href="first.html#flask">Flask 框架的简介</a></li>
<li class="toctree-l2"><a class="reference internal" href="first.html#python-flask-restful-services">使用 Python 和 Flask 实现 RESTful services</a></li>
<li class="toctree-l2"><a class="reference internal" href="first.html#id2">优化 web service 接口</a></li>
<li class="toctree-l2"><a class="reference internal" href="first.html#id3">加强 RESTful web service 的安全性</a></li>
<li class="toctree-l2"><a class="reference internal" href="first.html#id4">可能的改进</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="second.html">使用 Flask-RESTful 设计 RESTful API</a><ul>
<li class="toctree-l2"><a class="reference internal" href="second.html#restful">RESTful 服务器</a></li>
<li class="toctree-l2"><a class="reference internal" href="second.html#id1">路由</a></li>
<li class="toctree-l2"><a class="reference internal" href="second.html#id2">解析以及验证请求</a></li>
<li class="toctree-l2"><a class="reference internal" href="second.html#id3">生成响应</a></li>
<li class="toctree-l2"><a class="reference internal" href="second.html#id4">认证</a></li>
</ul>
</li>
<li class="toctree-l1 current"><a class="current reference internal" href="">使用 Flask 设计 RESTful 的认证</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#id1">示例代码</a></li>
<li class="toctree-l2"><a class="reference internal" href="#id2">用户数据库</a></li>
<li class="toctree-l2"><a class="reference internal" href="#id3">密码散列</a></li>
<li class="toctree-l2"><a class="reference internal" href="#id4">用户注册</a></li>
<li class="toctree-l2"><a class="reference internal" href="#id5">基于密码的认证</a></li>
<li class="toctree-l2"><a class="reference internal" href="#id6">基于令牌的认证</a></li>
<li class="toctree-l2"><a class="reference internal" href="#oauth">OAuth 认证</a></li>
</ul>
</li>
</ul>

          
        
      </div>
      &nbsp;
    <div class="wy-side-ad">
        <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <!-- 新模板广告 -->
        <ins class="adsbygoogle"
             style="display:inline-block;width:160px;height:600px"
             data-ad-client="ca-pub-3421553373953599"
             data-ad-slot="9570547632"></ins>
        <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
        </script>


        <!--百度统计代码-->

          <script>
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "//hm.baidu.com/hm.js?9adc7a1c86496c8e2bc61c4f8fc92d30";
          var s = document.getElementsByTagName("script")[0]; 
          s.parentNode.insertBefore(hm, s);
        })();
        </script>
    </div>

    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" role="navigation" aria-label="top navigation">
        <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
        <a href="index.html">Designing a RESTful API with Python and Flask</a>
      </nav>


      
      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
    <li><a href="index.html">Docs</a> &raquo;</li>
      
    <li>使用 Flask 设计 RESTful 的认证</li>
      <li class="wy-breadcrumbs-aside">
        
          <a href="_sources/third.txt" rel="nofollow"> View page source</a>
        
      </li>
  </ul>
  <hr/>
</div>
          <div role="main" class="document">
            
  <div class="section" id="flask-restful">
<span id="third"></span><h1>使用 Flask 设计 RESTful 的认证<a class="headerlink" href="#flask-restful" title="Permalink to this headline">¶</a></h1>
<p>今天我将要展示一个简单，不过很安全的方式用来保护使用 Flask 编写的 API，它是使用密码或者令牌认证的。</p>
<div class="section" id="id1">
<h2>示例代码<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<p>本文使用的代码能够在 github 上找到: <a class="reference external" href="https://github.com/miguelgrinberg/REST-auth">REST-auth</a> 。</p>
</div>
<div class="section" id="id2">
<h2>用户数据库<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>为了让给出的示例看起来像真实的项目，这里我将使用 Flask-SQLAlchemy 来构建用户数据库模型并且存储到数据库中。</p>
<p>用户的数据库模型是十分简单的。对于每一个用户，username 和 password_hash 将会被存储:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">db</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;users&#39;</span>
    <span class="nb">id</span> <span class="o">=</span> <span class="n">db</span><span class="o">.</span><span class="n">Column</span><span class="p">(</span><span class="n">db</span><span class="o">.</span><span class="n">Integer</span><span class="p">,</span> <span class="n">primary_key</span> <span class="o">=</span> <span class="bp">True</span><span class="p">)</span>
    <span class="n">username</span> <span class="o">=</span> <span class="n">db</span><span class="o">.</span><span class="n">Column</span><span class="p">(</span><span class="n">db</span><span class="o">.</span><span class="n">String</span><span class="p">(</span><span class="mi">32</span><span class="p">),</span> <span class="n">index</span> <span class="o">=</span> <span class="bp">True</span><span class="p">)</span>
    <span class="n">password_hash</span> <span class="o">=</span> <span class="n">db</span><span class="o">.</span><span class="n">Column</span><span class="p">(</span><span class="n">db</span><span class="o">.</span><span class="n">String</span><span class="p">(</span><span class="mi">128</span><span class="p">))</span>
</pre></div>
</div>
<p>出于安全原因，用户的原始密码将不被存储，密码在注册时被散列后存储到数据库中。使用散列密码的话，如果用户数据库不小心落入恶意攻击者的手里，他们也很难从散列中解析到真实的密码。</p>
<p>密码 <strong>决不能</strong> 很明确地存储在用户数据库中。</p>
</div>
<div class="section" id="id3">
<h2>密码散列<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
<p>为了创建密码散列，我将会使用 PassLib 库，一个专门用于密码散列的 Python 包。</p>
<p>PassLib 提供了多种散列算法供选择。custom_app_context 是一个易于使用的基于 sha256_crypt 的散列算法。</p>
<p>User 用户模型需要增加两个新方法来增加密码散列和密码验证功能:</p>
<div class="highlight-python"><div class="highlight"><pre>from passlib.apps import custom_app_context as pwd_context

    class User(db.Model):
        # ...

        def hash_password(self, password):
            self.password_hash = pwd_context.encrypt(password)

        def verify_password(self, password):
            return pwd_context.verify(password, self.password_hash)
</pre></div>
</div>
<p>hash_password() 函数接受一个明文的密码作为参数并且存储明文密码的散列。当一个新用户注册到服务器或者当用户修改密码的时候，这个函数将被调用。</p>
<p>verify_password() 函数接受一个明文的密码作为参数并且当密码正确的话返回 True 或者密码错误的话返回 False。这个函数当用户提供和需要验证凭证的时候调用。</p>
<p>你可能会问如果原始密码散列后如何验证原始密码的？</p>
<p>散列算法是单向函数，这就是意味着它们能够用于根据密码生成散列，但是无法根据生成的散列逆向猜测出原密码。然而这些算法是具有确定性的，给定相同的输入它们总会得到相同的输出。PassLib 所有需要做的就是验证密码，通过使用注册时候同一个函数散列密码并且同存储在数据库中的散列值进行比较。</p>
</div>
<div class="section" id="id4">
<h2>用户注册<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h2>
<p>在本文例子中，一个客户端可以使用 POST 请求到 /api/users 上注册一个新用户。请求的主体必须是一个包含 username 和 password 的 JSON 格式的对象。</p>
<p>Flask 中的路由的实现如下所示:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@app.route</span><span class="p">(</span><span class="s">&#39;/api/users&#39;</span><span class="p">,</span> <span class="n">methods</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;POST&#39;</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">new_user</span><span class="p">():</span>
    <span class="n">username</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">json</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;username&#39;</span><span class="p">)</span>
    <span class="n">password</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">json</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;password&#39;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">username</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">password</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">abort</span><span class="p">(</span><span class="mi">400</span><span class="p">)</span> <span class="c"># missing arguments</span>
    <span class="k">if</span> <span class="n">User</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="n">username</span> <span class="o">=</span> <span class="n">username</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">abort</span><span class="p">(</span><span class="mi">400</span><span class="p">)</span> <span class="c"># existing user</span>
    <span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="p">(</span><span class="n">username</span> <span class="o">=</span> <span class="n">username</span><span class="p">)</span>
    <span class="n">user</span><span class="o">.</span><span class="n">hash_password</span><span class="p">(</span><span class="n">password</span><span class="p">)</span>
    <span class="n">db</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">user</span><span class="p">)</span>
    <span class="n">db</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">jsonify</span><span class="p">({</span> <span class="s">&#39;username&#39;</span><span class="p">:</span> <span class="n">user</span><span class="o">.</span><span class="n">username</span> <span class="p">}),</span> <span class="mi">201</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;Location&#39;</span><span class="p">:</span> <span class="n">url_for</span><span class="p">(</span><span class="s">&#39;get_user&#39;</span><span class="p">,</span> <span class="nb">id</span> <span class="o">=</span> <span class="n">user</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">_external</span> <span class="o">=</span> <span class="bp">True</span><span class="p">)}</span>
</pre></div>
</div>
<p>这个函数是十分简单地。参数 username 和 password 是从请求中携带的 JSON 数据中获取，接着验证它们。</p>
<p>如果参数通过验证的话，新的 User 实例被创建。username 赋予给 User，接着使用 hash_password 方法散列密码。用户最终被写入数据库中。</p>
<p>响应的主体是一个表示用户的 JSON 对象，201 状态码以及一个指向新创建的用户的 URI 的 HTTP 头信息：Location。</p>
<p>注意：get_user 函数可以在 github 上找到完整的代码。</p>
<p>这里是一个用户注册的请求，发送自 curl:</p>
<div class="highlight-python"><div class="highlight"><pre>$ curl -i -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;username&quot;:&quot;miguel&quot;,&quot;password&quot;:&quot;python&quot;}&#39; http://127.0.0.1:5000/api/users
HTTP/1.0 201 CREATED
Content-Type: application/json
Content-Length: 27
Location: http://127.0.0.1:5000/api/users/1
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 19:56:39 GMT

{
  &quot;username&quot;: &quot;miguel&quot;
}
</pre></div>
</div>
<p>需要注意地是在真实的应用中这里可能会使用安全的的 HTTP (譬如：HTTPS)。如果用户登录的凭证是通过明文在网络传输的话，任何对 API 的保护措施是毫无意义的。</p>
</div>
<div class="section" id="id5">
<h2>基于密码的认证<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h2>
<p>现在我们假设存在一个资源通过一个 API 暴露给那些必须注册的用户。这个资源是通过 URL: /api/resource 能够访问到。</p>
<p>为了保护这个资源，我们将使用 HTTP 基本身份认证，但是不是自己编写完整的代码来实现它，而是让 Flask-HTTPAuth 扩展来为我们做。</p>
<p>使用 Flask-HTTPAuth，通过添加 login_required 装饰器可以要求相应的路由必须进行认证:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">flask.ext.httpauth</span> <span class="kn">import</span> <span class="n">HTTPBasicAuth</span>
<span class="n">auth</span> <span class="o">=</span> <span class="n">HTTPBasicAuth</span><span class="p">()</span>

<span class="nd">@app.route</span><span class="p">(</span><span class="s">&#39;/api/resource&#39;</span><span class="p">)</span>
<span class="nd">@auth.login_required</span>
<span class="k">def</span> <span class="nf">get_resource</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">jsonify</span><span class="p">({</span> <span class="s">&#39;data&#39;</span><span class="p">:</span> <span class="s">&#39;Hello, </span><span class="si">%s</span><span class="s">!&#39;</span> <span class="o">%</span> <span class="n">g</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">username</span> <span class="p">})</span>
</pre></div>
</div>
<p>但是，Flask-HTTPAuth 需要给予更多的信息来验证用户的认证，当然 Flask-HTTPAuth 有着许多的选项，它取决于应用程序实现的安全级别。</p>
<p>能够提供最大自由度的选择(可能这也是唯一兼容 PassLib 散列)就是选用 verify_password 回调函数，这个回调函数将会根据提供的 username 和 password 的组合的，返回 True(通过验证) 或者 Flase(未通过验证)。Flask-HTTPAuth 将会在需要验证 username 和 password 对的时候调用这个回调函数。</p>
<p>verify_password 回调函数的实现如下:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@auth.verify_password</span>
<span class="k">def</span> <span class="nf">verify_password</span><span class="p">(</span><span class="n">username</span><span class="p">,</span> <span class="n">password</span><span class="p">):</span>
    <span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="n">username</span> <span class="o">=</span> <span class="n">username</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">user</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">user</span><span class="o">.</span><span class="n">verify_password</span><span class="p">(</span><span class="n">password</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">False</span>
    <span class="n">g</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">user</span>
    <span class="k">return</span> <span class="bp">True</span>
</pre></div>
</div>
<p>这个函数将会根据 username 找到用户，并且使用 verify_password() 方法验证密码。如果认证通过的话，用户对象将会被存储在 Flask 的 g 对象中，这样视图就能使用它。</p>
<p>这里是用 curl 请求只允许注册用户获取的保护资源:</p>
<div class="highlight-python"><div class="highlight"><pre>$ curl -u miguel:python -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 30
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:02:25 GMT

{
  &quot;data&quot;: &quot;Hello, miguel!&quot;
}
</pre></div>
</div>
<p>如果登录失败的话，会得到下面的内容:</p>
<div class="highlight-python"><div class="highlight"><pre>$ curl -u miguel:ruby -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 401 UNAUTHORIZED
Content-Type: text/html; charset=utf-8
Content-Length: 19
WWW-Authenticate: Basic realm=&quot;Authentication Required&quot;
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:03:18 GMT

Unauthorized Access
</pre></div>
</div>
<p>这里我再次重申在实际的应用中，请使用安全的 HTTP。</p>
</div>
<div class="section" id="id6">
<h2>基于令牌的认证<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h2>
<p>每次请求必须发送 username 和 password 是十分不方便，即使是通过安全的 HTTP 传输的话还是存在风险，因为客户端必须要存储不加密的认证凭证，这样才能在每次请求中发送。</p>
<p>一种基于之前解决方案的优化就是使用令牌来验证请求。</p>
<p>我们的想法是客户端应用程序使用认证凭证交换了认证令牌，接下来的请求只发送认证令牌。</p>
<p>令牌是具有有效时间，过了有效时间后，令牌变成无效，需要重新获取新的令牌。令牌的潜在风险在于生成令牌的算法比较弱，但是有效期较短可以减少风险。</p>
<p>有很多的方法可以加强令牌。一个简单的强化方式就是根据存储在数据库中的用户以及密码生成一个随机的特定长度的字符串，可能过期日期也在里面。令牌就变成了明文密码的重排，这样就能很容易地进行字符串对比，还能对过期日期进行检查。</p>
<p>更加完善的实现就是不需要服务器端进行任何存储操作，使用加密的签名作为令牌。这种方式有很多的优点，能够根据用户信息生成相关的签名，并且很难被篡改。</p>
<p>Flask 使用类似的方式处理 cookies 的。这个实现依赖于一个叫做 itsdangerous 的库，我们这里也会采用它。</p>
<p>令牌的生成以及验证将会被添加到 User 模型中，其具体实现如下:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">itsdangerous</span> <span class="kn">import</span> <span class="n">TimedJSONWebSignatureSerializer</span> <span class="k">as</span> <span class="n">Serializer</span>

<span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">db</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">generate_auth_token</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">expiration</span> <span class="o">=</span> <span class="mi">600</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">Serializer</span><span class="p">(</span><span class="n">app</span><span class="o">.</span><span class="n">config</span><span class="p">[</span><span class="s">&#39;SECRET_KEY&#39;</span><span class="p">],</span> <span class="n">expires_in</span> <span class="o">=</span> <span class="n">expiration</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">s</span><span class="o">.</span><span class="n">dumps</span><span class="p">({</span> <span class="s">&#39;id&#39;</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">id</span> <span class="p">})</span>

    <span class="nd">@staticmethod</span>
    <span class="k">def</span> <span class="nf">verify_auth_token</span><span class="p">(</span><span class="n">token</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">Serializer</span><span class="p">(</span><span class="n">app</span><span class="o">.</span><span class="n">config</span><span class="p">[</span><span class="s">&#39;SECRET_KEY&#39;</span><span class="p">])</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">token</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">SignatureExpired</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">None</span> <span class="c"># valid token, but expired</span>
        <span class="k">except</span> <span class="n">BadSignature</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">None</span> <span class="c"># invalid token</span>
        <span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="s">&#39;id&#39;</span><span class="p">])</span>
        <span class="k">return</span> <span class="n">user</span>
</pre></div>
</div>
<p>generate_auth_token() 方法生成一个以用户 id 值为值，&#8217;id&#8217; 为关键字的字典的加密令牌。令牌中同时加入了一个过期时间，默认为十分钟(600 秒)。</p>
<p>验证令牌是在 verify_auth_token() 静态方法中实现的。静态方法被使用在这里，是因为一旦令牌被解码了用户才可得知。如果令牌被解码了，相应的用户将会被查询出来并且返回。</p>
<p>API 需要一个获取令牌的新函数，这样客户端才能申请到令牌:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@app.route</span><span class="p">(</span><span class="s">&#39;/api/token&#39;</span><span class="p">)</span>
<span class="nd">@auth.login_required</span>
<span class="k">def</span> <span class="nf">get_auth_token</span><span class="p">():</span>
    <span class="n">token</span> <span class="o">=</span> <span class="n">g</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">generate_auth_token</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">jsonify</span><span class="p">({</span> <span class="s">&#39;token&#39;</span><span class="p">:</span> <span class="n">token</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s">&#39;ascii&#39;</span><span class="p">)</span> <span class="p">})</span>
</pre></div>
</div>
<p>注意：这个函数是使用了 auth.login_required 装饰器，也就是说需要提供 username 和 password。</p>
<p>剩下来的就是决策客户端怎样在请求中包含这个令牌。</p>
<p>HTTP 基本认证方式不特别要求 usernames 和 passwords 用于认证，在 HTTP 头中这两个字段可以用于任何类型的认证信息。基于令牌的认证，令牌可以作为 username 字段，password 字段可以忽略。</p>
<p>这就意味着服务器需要同时处理 username 和 password 作为认证，以及令牌作为 username 的认证方式。verify_password 回调函数需要同时支持这两种方式:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@auth.verify_password</span>
<span class="k">def</span> <span class="nf">verify_password</span><span class="p">(</span><span class="n">username_or_token</span><span class="p">,</span> <span class="n">password</span><span class="p">):</span>
    <span class="c"># first try to authenticate by token</span>
    <span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">verify_auth_token</span><span class="p">(</span><span class="n">username_or_token</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">user</span><span class="p">:</span>
        <span class="c"># try to authenticate with username/password</span>
        <span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">query</span><span class="o">.</span><span class="n">filter_by</span><span class="p">(</span><span class="n">username</span> <span class="o">=</span> <span class="n">username_or_token</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">user</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">user</span><span class="o">.</span><span class="n">verify_password</span><span class="p">(</span><span class="n">password</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">False</span>
    <span class="n">g</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">user</span>
    <span class="k">return</span> <span class="bp">True</span>
</pre></div>
</div>
<p>新版的 verify_password 回调函数会尝试认证两次。首先它会把 username 参数作为令牌进行认证。如果没有验证通过的话，就会像基于密码认证的一样，验证 username 和 password。</p>
<p>如下的 curl 请求能够获取一个认证的令牌:</p>
<div class="highlight-python"><div class="highlight"><pre>$ curl -u miguel:python -i -X GET http://127.0.0.1:5000/api/token
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 139
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:04:15 GMT

{
  &quot;token&quot;: &quot;eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc&quot;
}
</pre></div>
</div>
<p>现在可以使用令牌获取资源:</p>
<div class="highlight-python"><div class="highlight"><pre>$ curl -u eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc:unused -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 30
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:05:08 GMT

{
  &quot;data&quot;: &quot;Hello, miguel!&quot;
}
</pre></div>
</div>
<p>需要注意的是这里并没有使用密码。</p>
</div>
<div class="section" id="oauth">
<h2>OAuth 认证<a class="headerlink" href="#oauth" title="Permalink to this headline">¶</a></h2>
<p>当我们讨论 RESTful 认证的时候，OAuth 协议经常被提及到。</p>
<p>那么什么是 OAuth？</p>
<p>OAuth 可以有很多的含义。最通常就是一个应用程序允许其它应用程序的用户的接入或者使用服务，但是用户必须使用应用程序提供的登录凭证。我建议阅读者可以浏览 <a class="reference external" href="http://en.wikipedia.org/wiki/OAuth">OAuth</a> 了解更多知识。</p>
</div>
</div>


          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
      
        <a href="second.html" class="btn btn-neutral" title="使用 Flask-RESTful 设计 RESTful API"><span class="fa fa-arrow-circle-left"></span> Previous</a>
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2014, Miguel.
    </p>
  </div>

  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
  
</footer>
        </div>
      </div>

    </section>

  </div>
  


  

    <script type="text/javascript">
        var DOCUMENTATION_OPTIONS = {
            URL_ROOT:'./',
            VERSION:'1.0',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
            HAS_SOURCE:  true
        };
    </script>
      <script type="text/javascript" src="_static/jquery.js"></script>
      <script type="text/javascript" src="_static/underscore.js"></script>
      <script type="text/javascript" src="_static/doctools.js"></script>

  

  
  
    <script type="text/javascript" src="_static/js/theme.js"></script>
  

  
  
  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.StickyNav.enable();
      });
  </script>
   

</body>
</html>